package com.qingmu.club.minaapi.controller.member;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 积分赠送 前端控制器
 * </p>
 *测试
 * @author duke
 * @since 2019-10-17
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "积分赠送相关(会员端小程序)", description = "积分赠送相关(会员端小程序)")
@RequestMapping("/member/integral")
public class MemberIntegralController {

    @Autowired
    UsersService usersService;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    IntegralSharePresentService integralSharePresentService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubUsersIntegralService clubUsersIntegralService;

    @Autowired
    UsersShareRelationService usersShareRelationService;

    @Autowired
    IntegralAttentionPresentService integralAttentionPresentService;

    @RequestMapping(value = "/onceSharePresent", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "首次分享送积分")
    public ResponseEntity onceSharePresent(
            @ApiParam(required = true, value = "B用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "A用户分享id") @RequestParam(required = true) String recommendId
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        ClubShop clubShop = this.clubShopService.getById(shopId);
        if (clubShop == null) {
            return ResponseObject.error(556, "门店不存在");
        }
        QueryWrapper<UsersShareRelation> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq(UsersShareRelation.SHOP_ID, shopId).eq(UsersShareRelation.USER_ID,userId).eq(UsersShareRelation.PARANT_USER_ID,recommendId);
        UsersShareRelation usersShareRelation = this.usersShareRelationService.getOne(queryWrapper2);
        if (usersShareRelation != null) {
            return ResponseObject.success();
        }

        if(userId.equals(recommendId)){
            return ResponseObject.success();
        }

        UsersShareRelation relation = new UsersShareRelation();
        relation.setUserId(userId);
        relation.setParantUserId(recommendId);
        relation.setShopId(shopId);
        boolean state = this.usersShareRelationService.save(relation);
        if (!state) {
            return ResponseObject.error();
        }

        QueryWrapper<IntegralSharePresent> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(IntegralSharePresent.CLUB_ID, clubShop.getClubId())
                .eq(IntegralSharePresent.STATUS, KeyValueDefine.ONLINE_STATUS); //启用
//                .(IntegralSharePresent.IS_ALWAYS.equals(0),IntegralSharePresent.START_TIME,)
        IntegralSharePresent sharePresent = this.integralSharePresentService.getOne(queryWrapper);
        if (sharePresent == null) {
            return ResponseObject.success(); //如果中台没设置积分赠送规则 直接返回一个空对象 不报错
        }

        Users recommend = this.usersService.getById(recommendId);
        String clubUserId = "";
        Integer userJf = 0 ;
        //用户关注门店的会员信息，如果没关注，分享之后就默认关注门店
        QueryWrapper<ClubUsers> clubUsersQueryWrapper = new QueryWrapper<>();
        clubUsersQueryWrapper.eq(ClubUsers.SHOP_ID, shopId).eq(ClubUsers.USER_ID, recommendId);//关注
        ClubUsers clubUsers = this.clubUsersService.getOne(clubUsersQueryWrapper);
        if (clubUsers == null) {

            //关注送积分
            QueryWrapper<IntegralAttentionPresent> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3
                    .eq(IntegralAttentionPresent.CLUB_ID, clubShop.getClubId())
                    .eq(IntegralAttentionPresent.STATUS,KeyValueDefine.ONLINE_STATUS);
            IntegralAttentionPresent attentionPresent = this.integralAttentionPresentService.getOne(queryWrapper3);
            if (attentionPresent != null) {
                userJf=attentionPresent.getPresentIntegral();
            }

            ClubUsers newClubUsers = new ClubUsers();
            newClubUsers.setUserId(recommend.getId());
            newClubUsers.setUserName(recommend.getUserName());
            newClubUsers.setUserSex(recommend.getUserSex());
            newClubUsers.setClubId(clubShop.getClubId());
            newClubUsers.setShopId(shopId);
            newClubUsers.setShopName(clubShop.getShopName());
            newClubUsers.setShopAvater(clubShop.getCover1());
            newClubUsers.setAttentionTime(new Date());
            newClubUsers.setAttentionStatus(KeyValueDefine.ATTENTION);//关注
            newClubUsers.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
            newClubUsers.setUserIcon(recommend.getUserIcon());
            newClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
            newClubUsers.setAttentionType(KeyValueDefine.ATTENTION_SHOP);//默认关注门店
            newClubUsers.setUserJf(sharePresent.getClickIntegral() + sharePresent.getShareIntegral()+userJf);
            boolean state2 = this.clubUsersService.save(newClubUsers);
            if (!state2) {
                return ResponseObject.error();
            }
            clubUserId = newClubUsers.getId();
        } else {
            clubUserId = clubUsers.getId();
            clubUsers.setUserJf(clubUsers.getUserJf()+sharePresent.getClickIntegral() + sharePresent.getShareIntegral());
            boolean state3 = this.clubUsersService.updateById(clubUsers);
            if (!state3) {
                return ResponseObject.error();
            }
        }

        ClubUsersIntegral one = new ClubUsersIntegral();
        one.setIntegralName("分享积分");
        one.setClubUsersId(clubUserId);
        one.setUserId(recommendId);
        one.setShopId(shopId);
        one.setIntegralNum(sharePresent.getClickIntegral() + sharePresent.getShareIntegral());//赠送分享积分+点击积分
        one.setType(1);
        one.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        one.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        one.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state1 = clubUsersIntegralService.save(one);
        if (!state1) {
            return ResponseObject.error();
        }

        ClubUsersIntegral threeRecommend = new ClubUsersIntegral();
        threeRecommend.setIntegralName("关注积分");
        threeRecommend.setClubUsersId(clubUserId);
        threeRecommend.setUserId(recommendId);
        threeRecommend.setShopId(shopId);
        threeRecommend.setIntegralNum(userJf);//关注积分
        threeRecommend.setType(1);
        threeRecommend.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        threeRecommend.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        threeRecommend.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state4 = clubUsersIntegralService.save(threeRecommend);
        if (!state4) {
            return ResponseObject.error();
        }

        return ResponseObject.success();
    }


    @RequestMapping(value = "/twiceSharePresent", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "二次分享送积分")
    public ResponseEntity twiceSharePresent(
            @ApiParam(required = true, value = "C用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "A用户分享id") @RequestParam(required = true) String recommendId1,
            @ApiParam(required = true, value = "B用户分享id") @RequestParam(required = true) String recommendId2
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "会员信息找不到");
        }
        ClubShop clubShop = this.clubShopService.getById(shopId);
        if (clubShop == null) {
            return ResponseObject.error(556, "门店不存在");
        }

        if(userId.equals(recommendId2)){
            return ResponseObject.success();
        }

        QueryWrapper<UsersShareRelation> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq(UsersShareRelation.SHOP_ID, shopId).eq(UsersShareRelation.USER_ID,userId).eq(UsersShareRelation.PARANT_USER_ID,recommendId2);
        UsersShareRelation usersShareRelation = this.usersShareRelationService.getOne(queryWrapper2);
        if (usersShareRelation != null) {
            return ResponseObject.success();
        }

        UsersShareRelation relation = new UsersShareRelation();
        relation.setUserId(userId);
        relation.setParantUserId(recommendId2);
        relation.setShopId(shopId);
        boolean state = this.usersShareRelationService.save(relation);
        if (!state) {
            return ResponseObject.error();
        }

        QueryWrapper<IntegralSharePresent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(IntegralSharePresent.CLUB_ID, clubShop.getClubId());
        IntegralSharePresent sharePresent = this.integralSharePresentService.getOne(queryWrapper);
        if (sharePresent == null) {
            return ResponseObject.success(); //如果中台没设置积分赠送规则 直接返回一个空对象 不报错
        }


        //用户关注门店的会员信息，如果没关注，分享之后就默认关注门店
        QueryWrapper<ClubUsers> clubUsersQueryWrapper1 = new QueryWrapper<>();
        clubUsersQueryWrapper1.eq(ClubUsers.SHOP_ID, shopId).eq(ClubUsers.USER_ID, recommendId1);//关注
        ClubUsers clubUsers = this.clubUsersService.getOne(clubUsersQueryWrapper1);


        String clubUserId = "";
        Integer userJf = 0 ;
        //用户关注门店的会员信息，如果没关注，分享之后就默认关注门店
        QueryWrapper<ClubUsers> clubUsersQueryWrapper2 = new QueryWrapper<>();
        clubUsersQueryWrapper2.eq(ClubUsers.SHOP_ID, shopId).eq(ClubUsers.USER_ID, recommendId2);//关注
        ClubUsers clubUsers2 = this.clubUsersService.getOne(clubUsersQueryWrapper2);

        if (clubUsers2 == null) {

            //关注送积分
            QueryWrapper<IntegralAttentionPresent> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3
                    .eq(IntegralAttentionPresent.CLUB_ID, clubShop.getClubId())
                    .eq(IntegralAttentionPresent.STATUS,1);
            IntegralAttentionPresent attentionPresent = this.integralAttentionPresentService.getOne(queryWrapper3);
            if (attentionPresent != null) {
                userJf=attentionPresent.getPresentIntegral();
            }

            Users users2 = this.usersService.getById(recommendId2);
            ClubUsers newClubUsers = new ClubUsers();
            newClubUsers.setUserId(users2.getId());
            newClubUsers.setUserName(users2.getUserName());
            newClubUsers.setUserSex(users2.getUserSex());
            newClubUsers.setClubId(clubShop.getClubId());
            newClubUsers.setShopId(shopId);
            newClubUsers.setShopName(clubShop.getShopName());
            newClubUsers.setShopAvater(clubShop.getCover1());
            newClubUsers.setAttentionTime(new Date());
            newClubUsers.setAttentionStatus(KeyValueDefine.ATTENTION);//关注
            newClubUsers.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
            newClubUsers.setUserIcon(users2.getUserIcon());
            newClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
            newClubUsers.setAttentionType(KeyValueDefine.ATTENTION_SHOP);//默认关注门店
            newClubUsers.setUserJf(sharePresent.getClickIntegral() + sharePresent.getShareIntegral()+userJf);
            boolean state2 = this.clubUsersService.save(newClubUsers);
            if (!state2) {
                return ResponseObject.error();
            }
            clubUserId = newClubUsers.getId();
        } else {
            clubUserId = clubUsers2.getId();
            clubUsers2.setUserJf(clubUsers2.getUserJf()+sharePresent.getClickIntegral() + sharePresent.getShareIntegral());
            boolean state3 = this.clubUsersService.updateById(clubUsers2);
            if (!state3) {
                return ResponseObject.error();
            }
        }

        ClubUsersIntegral oneRecommend = new ClubUsersIntegral();
        oneRecommend.setIntegralName("分享积分");
        oneRecommend.setClubUsersId(clubUsers.getId());
        oneRecommend.setUserId(recommendId1);
        oneRecommend.setShopId(shopId);
        oneRecommend.setIntegralNum(sharePresent.getTwiceShareIntegral());//赠送二次分享积分
        oneRecommend.setType(1);
        oneRecommend.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        oneRecommend.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        oneRecommend.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state1 = clubUsersIntegralService.save(oneRecommend);
        if (!state1) {
            return ResponseObject.error();
        }

        clubUsers.setUserJf(clubUsers.getUserJf()+sharePresent.getTwiceShareIntegral());
        boolean state3 = this.clubUsersService.updateById(clubUsers);
        if (!state3) {
            return ResponseObject.error();
        }

        ClubUsersIntegral twoRecommend = new ClubUsersIntegral();
        twoRecommend.setIntegralName("分享积分");
        twoRecommend.setClubUsersId(clubUserId);
        twoRecommend.setUserId(recommendId2);
        twoRecommend.setShopId(shopId);
        twoRecommend.setIntegralNum(sharePresent.getClickIntegral() + sharePresent.getShareIntegral());//赠送二次分享积分
        twoRecommend.setType(1);
        twoRecommend.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        twoRecommend.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        twoRecommend.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state2 = clubUsersIntegralService.save(twoRecommend);
        if (!state2) {
            return ResponseObject.error();
        }

        ClubUsersIntegral threeRecommend = new ClubUsersIntegral();
        threeRecommend.setIntegralName("关注积分");
        threeRecommend.setClubUsersId(clubUserId);
        threeRecommend.setUserId(recommendId2);
        threeRecommend.setShopId(shopId);
        threeRecommend.setIntegralNum(userJf);//关注送积分
        threeRecommend.setType(1);
        threeRecommend.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        threeRecommend.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        threeRecommend.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state4 = clubUsersIntegralService.save(threeRecommend);
        if (!state4) {
            return ResponseObject.error();
        }


        return ResponseObject.success();
    }

}
